package 数据结构OJ;

public class 回文链表_03 {

//      Definition for singly-linked list.
      public class ListNode {
          int val;
          ListNode next;
          ListNode(int x) { val = x; }
      }

    class Solution {
        public boolean isPalindrome(ListNode head) {
            //找出中间节点，快慢指针
            //找出中间位置
            if(head == null || head.next == null)
                return true;
            ListNode fast = head;
            ListNode low = head;
            //需要将后半段链表反转
            while(fast != null && low != null && fast.next != null) {
                fast = fast.next.next;
                low = low.next;
            }
            //找到链表中间位置
            ListNode mid = low;
            //反转后半段链表

            if(mid == head)
                return true;
            ListNode prev = null;
            ListNode cur = mid;
            while(cur != null) {
                ListNode temp = cur;
                cur = cur.next;
                temp.next = prev;
                prev = temp;
            }
            //俩个链表开始从前向后遍历
            fast = head;
            while(head != null && prev != null) {
                if(head.val != prev.val) {
                    return false;
                }
                head = head.next;
                prev = prev.next;
            }
            return true;
        }
    }
}
